<template>
  <a-card :bordered="false" class="card-area">
    <div>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
        accept=".xls, .xlsx"
      >
        <a-button type="primary" icon="import" :loading="loading">批量上传</a-button>
      </a-upload>

      <a-button type="primary" icon="import" style="margin-left:10px" @click="editHandle('')">新增数据</a-button>
    </div>
    <a-table
      :loading="loading"
      :columns="columns"
      :dataSource="dataSource"
      :rowKey="dataSource => dataSource.id"
      @change="handleTableChange"
      :pagination="pagination"
    >
      <span slot="img" slot-scope="text,record,index">
        <img style="width:80px;height:80px" :src="record.goodsImg" alt />
      </span>
      <template slot="status" slot-scope="text,record,index">
        <div>
          <a-tag v-if="record.onSale==0">审核中</a-tag>
          <a-tag v-if="record.onSale==1" color="blue">审核成功</a-tag>
          <a-tag v-if="record.onSale==2" color="red">审核失败</a-tag>
        </div>
      </template>
      <span slot="action" slot-scope="record">
        <a href="javascript:;" @click.stop="editHandle(record)">编辑</a>
        <!-- <a-divider type="vertical" /> -->
        <!-- <a href="javascript:;" @click.stop="deleteRecord(record)">删除</a> -->
      </span>
    </a-table>

    <!-- 弹出修改框 -->
    <a-modal
      :title="modal_title"
      :visible="model_visible"
      :confirmLoading="loading"
      width="60%"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form">
        <!-- 客户姓名 -->
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="ID">
          <a-input v-decorator="['id']" placeholder="ID" :disabled="true" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品名称">
          <a-input
            v-decorator="['goodsName',{rules:[{required:true,message:'商品名称'}]}]"
            placeholder="商品名称"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品拼音(首字单个拼音)">
          <a-input
            v-decorator="['goodsSubtitle',{rules:[{required:true,message:'商品拼音'}]}]"
            placeholder="商品拼音（首字单个拼音，如a）"
            oninput="this.value=this.value.replace(/[\u4e00-\u9fa5\d]/g,'');"
            maxlength="1"
          ></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商家名称">
          <a-select
            v-decorator="['storeId',{rules:[{required:true,message:'商家名称'}]}]"
            placeholder="商家名称"
          >
            <a-select-option
              v-for="(item,index) in shop_arr"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input
            v-decorator="['sort']"
            placeholder="排序"
            oninput="value=value.replace(/[^\d]/g,'')"
          ></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="一级类型">
          <a-select
            v-decorator="['pid',{rules:[{required:true,message:'一级类型'}]}]"
            placeholder="一级类型"
            @change="handleFirstSelect"
          >
            <a-select-option
              v-for="(item,index) in first_sel_arr"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="二级类型">
          <a-select
            v-decorator="['cid',{rules:[{required:true,message:'二级类型'}]}]"
            placeholder="二级类型"
          >
            <a-select-option
              v-for="(item,index) in second_sel_arr"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="品牌">
          <a-select v-decorator="['bid',{rules:[{required:true,message:'品牌'}]}]" placeholder="品牌">
            <a-select-option
              v-for="(item,index) in brand_arr"
              :key="index"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品价格">
          <a-input
            v-decorator="['goodsPrice',{rules:[{required:true,message:'商品价格'}]}]"
            placeholder="商品价格"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品审核">
          <a-select
            v-decorator="['onSale',{rules:[{required:true,message:'商品审核'}]}]"
            placeholder="商品审核"
          >
            <a-select-option
              v-for="(item,index) in onSale_arr"
              :key="index"
              :value="item.value"
            >{{item.label}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图片">
          <a-upload
            :action="modal_action"
            listType="picture-card"
            :fileList="fileList"
            @preview="handlePreview"
            @change="handleChange"
            :beforeUpload="beforeUpload"
            accept=".jpg, .png, .jpeg, .JPG, .PNG, .JPEG"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <!-- ,{rules:[{required:true,message:'请上传图片'}]} -->
          <a-input v-decorator="['goodsImg']" placeholder="图片" :disabled="true" />
        </a-form-item>
        <a-form-item
          :labelCol="{ lg: { span: 7 },sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 15 }, sm: { span: 17 } }"
          label="商品详情"
        >
          <a-input v-decorator="['goodsDetails']" style="display:none" :disabled="true"></a-input>
          <tinymce-editor ref="editor" v-model="msg" @onClick="onClick"></tinymce-editor>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { postAction, getAction, baseUrl } from '@/api/manage'
import TinymceEditor from '@/components/TinyEditor/tiny-editor'

export default {
  data() {
    return {
      columns: [
        {
          title: 'ID',
          align: 'center',
          dataIndex: 'id'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName',
          width: 200
        },
        { title: '排序', align: 'center', dataIndex: 'sort' },
        {
          title: '商品类型',
          align: 'center',
          dataIndex: 'typeName'
        },
        {
          title: '商家名称',
          align: 'center',
          dataIndex: 'storename'
        },
        {
          title: '品牌',
          align: 'center',
          dataIndex: 'brandname'
        },
        {
          title: '商品价格',
          align: 'center',
          dataIndex: 'goodsPrice'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'onSale',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '图片',
          align: 'center',
          dataIndex: 'goodsImg',
          scopedSlots: { customRender: 'img' }
        },
        {
          title: '操作',
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          key: 'action'
        }
      ],
      dataSource: [],
      tokenHeader: {
        authorization: 'authorization-text'
      },
      importExcelUrl: `${baseUrl}/goods/uploadexcel`,
      pagination: {
        total: 0,
        pageSize: 10,
        current: 1,
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      },
      queryParam: {
        page: 1, //第几页
        size: 10 //每页中显示数据的条数
      },
      model_visible: false,
      form: this.$form.createForm(this), // 只有这样注册后，才能通过表单拉取数据
      labelCol: {
        lg: {
          span: 7
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        lg: {
          span: 10
        },
        sm: {
          span: 17
        }
      },
      fileList: [],
      modal_title: '',
      loading: false,
      modal_action: `${baseUrl}/file/uploadImg`,
      first_sel_arr: [],
      second_sel_arr: [],
      msg: null,
      shop_arr: [],
      onSale_arr: [{ value: 0, label: '审核中' }, { value: 1, label: '审核成功' }, { value: 2, label: '审核失败' }],
      brand_arr: []
    }
  },
  components: {
    TinymceEditor
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      this.loading = true
      postAction('/goods/all', this.queryParam).then(res => {
        this.loading = false
        this.dataSource = res.data
        this.getSelect()
        this.getShopSelect()
        this.getBid()
        const pagination = { ...this.pagination }
        pagination.total = res.total
        this.pagination = pagination
      })
    },
    getSelect() {
      postAction('/sort/pid', '').then(res => {
        this.first_sel_arr = res.pid
      })
    },
    getShopSelect() {
      postAction('/merchant/all', '').then(res => {
        this.shop_arr = res.data
      })
    },
    getBid() {
      postAction('/brand/all', '').then(res => {
        // console.log(res)
        this.brand_arr = res.data
      })
    },
    handleImportExcel({ file, fileList }) {
      this.loading = true
      if (file.status == 'done') {
        this.loading = false
        fileList = fileList.map(item => {
          if (item.response.code == 0 && item.response.status == 0) {
            this.getData()
          }
          this.$message.info(item.response.message)
        })
      }
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.queryParam.page = pagination.current
      this.queryParam.size = pagination.pageSize
      this.getData()
    },
    //打开弹出框并传参
    editHandle(item) {
      if (item) {
        setTimeout(() => {
          this.modal_title = '修改'
          const obj = {
            uid: '-1',
            name: 'xxx.png',
            status: 'done',
            url: item.goodsImg
          }
          this.fileList.push(obj)
          this.msg = item.goodsDetails
          this.handleFirstSelect(item.goodsTypePid)
          this.form.setFieldsValue({
            id: item.id,
            goodsName: item.goodsName,
            goodsImg: item.goodsImg,
            pid: item.goodsTypePid,
            cid: item.goodsTypeId,
            goodsPrice: item.goodsPrice,
            storeId: item.storeId,
            onSale: item.onSale,
            goodsSubtitle: item.goodsSubtitle,
            bid: item.bid,
            sort: item.sort
          })
        })
      } else {
        this.fileList = []
        if (this.msg) {
          this.clear()
        }
        this.form.resetFields()
        this.modal_title = '新增'
      }
      this.model_visible = true
    },
    //关闭弹出框并发起请求
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          this.form.setFieldsValue({
            goodsDetails: this.msg
          })
          postAction('/goods/addgoods', this.form.getFieldsValue()).then(res => {
            this.loading = false
            this.model_visible = false
            this.fileList = []
            this.getData()
          })
        }
      })
    },
    //关闭弹出框
    handleCancel() {
      this.fileList = []
      this.form.resetFields()
      this.clear()
      this.model_visible = false
    },
    //点击预览图标时的回调
    handlePreview(file) {
      // console.log(2222222222222222222222)
      // this.previewImage = file.url || file.thumbUrl
      // this.previewVisible = true
      
    },
    //上传文件改变时的状态
    handleChange({ file, fileList }) {
      this.fileList = fileList
      if (file.status == 'done') {
        fileList = fileList.map(item => {
          this.form.setFieldsValue({
            goodsImg: item.response.data
          })
        })
      } else if (file.status == 'removed') {
        this.form.setFieldsValue({
          goodsImg: ''
        })
      }
    },
    //一级被选择触发
    handleFirstSelect(val) {
      postAction('/sort/cid', {
        id: val
      }).then(res => {
        // console.log(res)
        this.second_sel_arr = res.data
      })
    },
    onClick(e, t) {
      // console.log(e)
      // console.log(t)
      // console.log(this.msg)
    },
    // 清空富文本内容
    clear() {
      // console.log(this.$refs.editor)
      this.$refs.editor.clear()
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isJPG) {
        this.$message.error('仅支持jpeg/png/jpg格式!')
      }
      // const isLt2M = file.size / 1024 / 1024 < 5
      // if (!isLt2M) {
      //   this.$message.error('上传不能超过5MB!')
      // }
      return isJPG
    }
  }
}
</script>